package com.library.dao;

import com.library.bean.Book;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Repository
public class BookDao {

    private final static String NAMESPACE = "com.library.dao.BookDao.";
    @Resource
    private SqlSessionTemplate sqlSessionTemplate;

    public int matchBook(final String searchWord) {//这个方法是用来判断模糊查询是否有结果的
        String search = "%" + searchWord + "%";//模糊查询的关键词为searchWord，加上%传给sql语句实现模糊查询
        return sqlSessionTemplate.selectOne(NAMESPACE + "matchBook", search);//selectOne方法和selectList方法类似，
        // 但是selectOne只能查询一条记录，超过一条会报错
    }

    public ArrayList<Book> queryBook(final String searchWord) {//传入查询的关键词
        String search = "%" + searchWord + "%";//模糊查询
        List<Book> result = sqlSessionTemplate.selectList(NAMESPACE + "queryBook", search);
        //这一句是调用sqlSessionTemplate的查询方法了，然后把查询的结果储存在List<Book>
        return (ArrayList<Book>) result;//返回模糊查询的结果
    }

    public ArrayList<Book> getAllBooks() {
        List<Book> result = sqlSessionTemplate.selectList(NAMESPACE + "getAllBooks");
        //这个方法是查询所有的书籍的结果
        return (ArrayList<Book>) result;
    }

    public int addBook(final Book book) { //这个方法是插入书籍的方法
        return sqlSessionTemplate.insert(NAMESPACE + "addBook", book);
    }


    public Book getBook(final long bookId) {
        return sqlSessionTemplate.selectOne(NAMESPACE + "getBook", bookId);
    }

    public int editBook(final Book book) {
        return sqlSessionTemplate.update(NAMESPACE + "editBook", book);
    }

    public int deleteBook(final long bookId) {
        return sqlSessionTemplate.delete(NAMESPACE + "deleteBook", bookId);
    }
}
